<template>
  <div class="category-management">
    <h1>菜品分类管理</h1>
    
    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>
    
    <!-- 分类表格 -->
    <el-table 
      :data="categoryList" 
      border 
      style="width: 100%" 
      v-loading="loading"
      :default-sort="{ prop: 'categoryId', order: 'ascending' }"
    >
      <el-table-column 
        prop="categoryId" 
        label="分类ID" 
        width="120" 
        align="center"
        sortable
      ></el-table-column>
      <el-table-column 
        prop="categoryName" 
        label="分类名称" 
        width="200"
        sortable
      ></el-table-column>
      <el-table-column 
        prop="description" 
        label="分类描述"
        sortable
      ></el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(row.categoryId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑分类对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="500px"
      @closed="resetForm"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="formData.categoryName" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入分类描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 分类列表数据
const categoryList = ref([])
const loading = ref(false)

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增分类')
const formData = ref({
  categoryId: null,
  categoryName: '',
  description: ''
})
const formRef = ref(null)

// 表单验证规则
const formRules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize
    }
    
    const response = await axios.get('http://localhost:8081/categories/list', { params })
    
    if (response.data.code === 200) {
      categoryList.value = response.data.data.records || response.data.data.list || response.data.data
      pagination.value.total = response.data.data.total || response.data.data.length || 0
    } else {
      ElMessage.error(response.data.message || '获取分类列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 每页条数变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchCategories()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchCategories()
}

// 新增分类
const handleAdd = () => {
  dialogTitle.value = '新增分类'
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  formData.value = {
    categoryId: row.categoryId,
    categoryName: row.categoryName,
    description: row.description
  }
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (categoryId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`http://localhost:8081/categories/delete/${categoryId}`)
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchCategories()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    let response
    if (formData.value.categoryId) {
      // 编辑
      response = await axios.post('http://localhost:8081/categories/update', formData.value)
    } else {
      // 新增
      response = await axios.post('http://localhost:8081/categories/add', formData.value)
    }
    
    if (response.data.code === 200) {
      ElMessage.success(dialogTitle.value + '成功')
      dialogVisible.value = false
      fetchCategories()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    if (error.name !== 'ValidateError') {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    categoryId: null,
    categoryName: '',
    description: ''
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.category-management {
  padding: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-start;
  margin-top: 20px;
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>